package edu.c06190115.cardiac;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.os.SystemClock;
import android.widget.Chronometer;


public class SetAlgorithm extends Activity {

	private int current;
	private FileRead fileReader;
	private Chronometer chronometer;
	private String fileName;
	private Chronometer chronometer2;
	private int saveMe;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set_algorithm);
		Intent intent = this.getIntent();
		fileName = intent.getStringExtra("edu.c06190115.cardiac.file_name");
		String algorithmName = intent.getStringExtra("edu.c06190115.cardiac.algorithm_name");
		fileReader = new FileRead(algorithmName, this.getApplicationContext());
		current = 0;
		populateFields(current);

		chronometer = (Chronometer) findViewById(R.id.chronometer);
		chronometer.setBase(SystemClock.elapsedRealtime());
		chronometer.start();
	}

	public void myClickListener(View view){
		int next;
		int previous;
		saveMe = current;
		switch(view.getId()){
		case R.id.Yes:
			next = fileReader.stepArr[current].getNextStep();
			current = next;
			writeToFile("Yes");
			populateFields(current);
			break;
		case R.id.No:
			next = fileReader.stepArr[current].getNoNext();
			current = next;
			writeToFile("No");
			populateFields(current);
			break;
		case R.id.Switch:
			changeColor();
			if (fileReader.stepArr[current].hasTimer == 1){
				chronometer2.setVisibility(View.VISIBLE);
				chronometer2.setBase(SystemClock.elapsedRealtime());
				chronometer2.start();
			}
			break;
		case R.id.Next:

			if (fileReader.stepArr[current].numOfSteps == 2){
				current = current + 1;
			} else if (fileReader.stepArr[current].numOfSteps == 3){
				current = current + 2;
			} 
			next = fileReader.stepArr[current].getNextStep();
			current = next;
			writeToFile("Next");
			populateFields(current);
			break;
		case R.id.Previous:
			previous = fileReader.stepArr[current].getPrevStep();
			current = previous;
			writeToFile("Previous");
			populateFields(current);
			break;
		}
	}

	public void changeColor(){
		int index = 0;
		TextView text2 = (TextView) findViewById(R.id.editText2);
		TextView text1 = (TextView) findViewById(R.id.editText1);
		TextView text3 = (TextView) findViewById(R.id.editText3);


		if (text1.getCurrentTextColor() == Color.WHITE){
			index = 1;
		}
		if (text2.getCurrentTextColor() == Color.WHITE){
			index = 2;
		}
		if (fileReader.stepArr[current].numOfSteps == 3 && text3.getCurrentTextColor() == Color.WHITE){
			index = 3;
		} 

		if (index == 1){
			text1.setTextColor(Color.DKGRAY);
			text2.setTextColor(Color.WHITE);
			text3.setTextColor(Color.DKGRAY);
		} else if (index == 2 && fileReader.stepArr[current].numOfSteps == 3){
			text1.setTextColor(Color.DKGRAY);
			text2.setTextColor(Color.DKGRAY);
			text3.setTextColor(Color.WHITE);
		} else if (index == 2 && fileReader.stepArr[current].numOfSteps == 2){
			text1.setTextColor(Color.WHITE);
			text2.setTextColor(Color.DKGRAY);
		} else if (index == 3 && fileReader.stepArr[current].numOfSteps == 3){
			text1.setTextColor(Color.WHITE);
			text2.setTextColor(Color.DKGRAY);
			text3.setTextColor(Color.DKGRAY);
		}	
	}
	public void writeToFile(String buttonType) {
		try {
			long elapsedMillis = SystemClock.elapsedRealtime() - chronometer.getBase();
			long x = elapsedMillis / 1000;
			String seconds, minutes;
			if (x / 10 == 0) {
				seconds = String.format("0%d", x % 60);
			} else {
				seconds = String.format("%d", x % 60);	
			}
			x /= 60;
			if (x / 10 == 0) {
				minutes = String.format("0%d", x % 60);
			} else {
				minutes = String.format("%d", x % 60);
			}
			Calendar c = Calendar.getInstance();
			String data = buttonType + " " + c.get(Calendar.MONTH) + "/" + c.get(Calendar.DATE) + "/" + 
					+ c.get(Calendar.YEAR) + "-" + c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE) + ":" 
					+ c.get(Calendar.SECOND) + " " + ((TextView)findViewById(R.id.editText2)).getText() + " " 
					+ minutes + ":" + seconds + "\n"; 
			File root = new File(Environment.getExternalStorageDirectory(), "Cardiac");
			File gpxfile = new File(root, fileName);
			FileWriter writer = new FileWriter(gpxfile, true);
			BufferedWriter bufferWritter = new BufferedWriter(writer);
			bufferWritter.write(data);
			bufferWritter.close();
		}
		catch(IOException e) {
			e.printStackTrace();
		}
	}

	public void populateFields(int index){
		Button yesButton;
		Button noButton;
		Button switchButton;
		Button nextButton;
		Button previousButton;
		TextView textStep;

		yesButton = (Button)findViewById(R.id.Yes);
		noButton = (Button)findViewById(R.id.No);
		switchButton = (Button)findViewById(R.id.Switch);
		nextButton = (Button)findViewById(R.id.Next);
		previousButton = (Button)findViewById(R.id.Previous);
		TextView text2 = (TextView) findViewById(R.id.editText2);
		TextView text1 = (TextView) findViewById(R.id.editText1);
		TextView text3 = (TextView) findViewById(R.id.editText3);

		text2.setText("");
		text3.setText("");
		text1.setText("");
		text2.setTextColor(Color.WHITE);
		chronometer2 = (Chronometer) findViewById(R.id.chronometerHide);
		textStep = (TextView)findViewById(R.id.stepTime);

		try {
			//check to see choice
			if (fileReader.stepArr[index].hasChoice() == 1){
				yesButton.setVisibility(View.VISIBLE);
				noButton.setVisibility(View.VISIBLE);
				nextButton.setVisibility(View.INVISIBLE);
			} else {
				yesButton.setVisibility(View.INVISIBLE);
				noButton.setVisibility(View.INVISIBLE);
				nextButton.setVisibility(View.VISIBLE);
			}
			if (fileReader.stepArr[index].getPrevStep() == 99) {
				previousButton.setVisibility(View.INVISIBLE);
			} else {
				previousButton.setVisibility(View.VISIBLE);
			}
			if (fileReader.stepArr[index].hasTimer == 1){

				chronometer2.setVisibility(View.VISIBLE);

				textStep.setVisibility(View.VISIBLE);
				chronometer2.setBase(SystemClock.elapsedRealtime());
				chronometer2.start();
			} else {
				chronometer2.setVisibility(View.INVISIBLE);
				textStep.setVisibility(View.INVISIBLE);

			}
			//--------------------------------
			//setting the textFields
			if (fileReader.stepArr[index].getNumOfSteps()== 1){

				text2.setText(fileReader.stepArr[index].getStepInfo());	
				switchButton.setVisibility(View.INVISIBLE);
			}
			else if (fileReader.stepArr[index].getNumOfSteps() == 2){

				text1.setText(fileReader.stepArr[index].getStepInfo());
				text1.setTextColor(Color.WHITE);
				text2.setText(fileReader.stepArr[index + 1].getStepInfo());
				text2.setTextColor(Color.DKGRAY);
				switchButton.setVisibility(View.VISIBLE);

			}
			else if (fileReader.stepArr[index].getNumOfSteps() ==3){

				text1.setText(fileReader.stepArr[index].getStepInfo());
				text1.setTextColor(Color.WHITE);
				text2.setText(fileReader.stepArr[index+1].getStepInfo());
				text2.setTextColor(Color.DKGRAY);

				text3.setText(fileReader.stepArr[index+2].getStepInfo());
				text3.setTextColor(Color.DKGRAY);
				switchButton.setVisibility(View.VISIBLE);

			}
			//------------------------
			if (fileReader.stepArr[index].hasTimer() == 1){
				//Show timer on screen
				//Start timer upon click 

			}
		} catch (Exception e) {
			new AlertDialog.Builder(this)
			.setTitle("Algorithm End")
			.setMessage("Are you sure you want to finish?")
			.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) { 
					finish();
					Intent emailIntent = new Intent(Intent.ACTION_SEND);
					emailIntent.setType("text/Message");
					File root = new File(Environment.getExternalStorageDirectory(), "Cardiac");
					File gpxfile = new File(root, fileName);
					emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(gpxfile));
					startActivity(Intent.createChooser(emailIntent, "Send report as attachment via..."));
				}
			})
			.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) { 
					current = saveMe;
					populateFields(current);
				}
			})
			.setIcon(android.R.drawable.ic_dialog_alert)
			.show();
		}
	}

	DialogInterface.OnClickListener yesNoListener = 
			new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog,int whatWasClicked) {

			switch (whatWasClicked) {
			case DialogInterface.BUTTON_POSITIVE:
				finish();
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				break;
			default:
				break;
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.set_algorithm, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.goHome:
			finish();
			return true;
		}
		return false;
	}
}
